package com.rla.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.annotation.Anonymous;
import com.rla.common.constant.Globebill;
import com.rla.common.constant.OrderConstants;
import com.rla.common.core.controller.BaseController;
import com.rla.common.core.domain.R;
import com.rla.domain.MallOrderPay;
import com.rla.domain.bo.MallOnlinePayBo;
import com.rla.domain.bo.MallOrderBo;
import com.rla.domain.vo.MallOrderPayVo;
import com.rla.domain.vo.MallOrderVo;
import com.rla.mapper.MallOrderPayMapper;
import com.rla.service.IMallOrderOnlinePayService;
import com.rla.service.IMallOrderPayService;
import com.rla.service.IMallOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mall/order/onlinePay")
public class MallOrderOnlinePayController extends BaseController {

    private final IMallOrderOnlinePayService mallOrderOnlinePayService;
    private final IMallOrderService mallOrderService;
    private final MallOrderPayMapper mallOrderPayMapper;



    /*
    * 来钱乐支付
    * */
    @PostMapping("/lql/pay")
    public R<Map<String,Object>> lqlPay(@Validated @RequestBody MallOnlinePayBo bo) {

        MallOrderVo orderVo = mallOrderService.getPayInfoById(bo.getOrderId());
        List<MallOrderPayVo> wechatPay = mallOrderPayMapper.selectVoList(Wrappers.lambdaUpdate(MallOrderPay.class)
                .eq(MallOrderPay::getOrderId, bo.getOrderId())
                .eq(MallOrderPay::getPayMode, OrderConstants.WECHAT));

        int amount = wechatPay.get(0).getPaymentAmount().multiply(new BigDecimal("100")).intValue();

        JSONObject jo = new JSONObject();
        jo.put("sn", Globebill.sn);
        jo.put("appId", Globebill.appId);
        jo.put("payModeId", Globebill.payModeId);
        jo.put("tradeAmount", amount);
        jo.put("outTransId", bo.getOrderId());
        jo.put("userOpenId", orderVo.getOpenId());
        //TODO 回调地址正式换成服务器回调地址
        jo.put("notifyUrl", Globebill.notifyUrl);
        String api = "/qrcode/pay";
        return R.ok(mallOrderOnlinePayService.lqlPay(jo,api));
    }

    /*
    * 来钱乐退款
    * */
    @PostMapping("/lql/refund")
    public R<Map<String,Object>> lqlRefund(@Validated @RequestBody MallOnlinePayBo bo) {

        MallOrderVo orderVo = mallOrderService.getPayInfoById(bo.getOrderId());

        List<MallOrderPayVo> wechatPay = mallOrderPayMapper.selectVoList(Wrappers.lambdaUpdate(MallOrderPay.class).eq(MallOrderPay::getOrderId, bo.getOrderId())
                .eq(MallOrderPay::getPayMode, OrderConstants.WECHAT));

        int amount = wechatPay.get(0).getPaymentAmount().multiply(new BigDecimal("100")).intValue();

        JSONObject jo = new JSONObject();
        jo.put("sn", Globebill.sn);
        jo.put("outTransId","T"+ bo.getOrderId());
        jo.put("tradeAmount", amount);
        jo.put("notifyUrl", Globebill.notifyUrl);
        //原交易流水号
        jo.put("sourceTradeId", wechatPay.get(0).getRemark());

        String api = "/qrcode/refund";
        return R.ok(mallOrderOnlinePayService.lqlPay(jo,api));
    }



    /**
     * 商户号 1
     * 支付回调接口，微信支付成功后会自动调用
     */
    @Anonymous
    @PostMapping("/lql/callback")
    public R<Boolean>  lqlNotifyCallback(@RequestBody Map<String, String> map,  HttpServletRequest request, HttpServletResponse response) {
        mallOrderOnlinePayService.lqlNotifyCallback(map);
        return R.ok(true);
    }

    /*
    *
    * 急速退款（未发货前）只能退当天12点之前的
    * */
    @PostMapping("/quick/refund")
    public R<Boolean> quickRefund(@Validated @RequestBody MallOnlinePayBo bo) {

        MallOrderVo orderVo = mallOrderService.queryById(bo.getOrderId());

        List<MallOrderPayVo> wechatPay = mallOrderPayMapper.selectVoList(Wrappers.lambdaUpdate(MallOrderPay.class).eq(MallOrderPay::getOrderId, bo.getOrderId()));

        for (MallOrderPayVo vo : wechatPay) {
            //来钱乐微信退款
            if (vo.getPayMode().equals(OrderConstants.WECHAT)) {
                int amount = vo.getPaymentAmount().multiply(new BigDecimal("100")).intValue();
                JSONObject jo = new JSONObject();
                jo.put("sn", Globebill.sn);
                jo.put("outTransId","T"+ bo.getOrderId());
                jo.put("tradeAmount", amount);
                jo.put("payModeId", 1036);
                jo.put("sourceTradeId", vo.getRemark());
                jo.put("notifyUrl", Globebill.notifyUrl);
                String api = "/qrcode/refund";
                Map<String, Object> map = mallOrderOnlinePayService.lqlPay(jo, api);
                //退款成功不会回调，根据返回结果处理
                mallOrderOnlinePayService.orderRefund(orderVo.getUserId(),orderVo.getId(),vo.getPaymentAmount(),vo.getId(),OrderConstants.WECHAT,map);
            }
            if (vo.getPayMode().equals(OrderConstants.BALANCE)){
                mallOrderOnlinePayService.orderRefund(orderVo.getUserId(),orderVo.getId(),vo.getPaymentAmount(),vo.getId(),OrderConstants.BALANCE,null);
            }
        }

        //更改订单状态
        MallOrderBo mallOrderBo = new MallOrderBo();
        mallOrderBo.setId(orderVo.getId());
        mallOrderBo.setOrderStatus(OrderConstants.AFTER);
        mallOrderBo.setOnlinePayTime(DateUtil.now());
        mallOrderBo.setBackStatus("99");//完成退款标志
        Boolean b = mallOrderService.updateByBo(mallOrderBo);

        return R.ok(true);
    }


}
